#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <strings.h>
#include <errno.h>

#include <cstring>
#include <functional>
#include <string>   
#include <iostream>
#include <unordered_map>
#include "log.hpp"

const int defaultport = 8888;
const char *defaultip = "0.0.0.0";
const int SIZE = 1024;

typedef std::function<const std::string(const std::string)> func_;

Log lg_;

enum
{
    SOCKET_ERR = 1,
    BIND_ERR
};

class UdpServe
{
public:
    UdpServe(const int &port = defaultport, const std::string &ip = defaultip)
        : port_(port), ip_(ip)
    {
    }

    // 进行初始化 , 将公网IP 和 端口 与套接字进行绑定
    void Init()
    {
        // 1. 初始化
        sockfd_ = socket(AF_INET, SOCK_DGRAM, 0); // 确定网络文件描述符
        if (sockfd_ < 0)
        {
            lg_(Fatal, "socket fail : errno message : %s , errno : %d ", strerror(errno), errno);
            exit(SOCKET_ERR);
        }
        // 2. bind连接
        struct sockaddr_in sockad;
        bzero(&sockad, sizeof(sockad));
        sockad.sin_family = AF_INET;
        sockad.sin_port = htons(port_);
        sockad.sin_addr.s_addr = inet_addr(ip_.c_str());

        int len = sizeof(sockad);
        if (bind(sockfd_, (const struct sockaddr *)&sockad, len) < 0) // 完成绑定
        {
            lg_(Fatal, "bind fail : errno message : %s , errno : %d ", strerror(errno), errno);
            exit(BIND_ERR);
        }
    }

    void New_Client(struct sockaddr_in& client,const std::string& clientip , const uint16_t clientport)
    {
        if(!all_client.count(clientip))
        {
            std::string wolcome = "new member add to the room : [" + clientip + ":" + std::to_string(clientport) + "]";
            std::cout << wolcome << std::endl;
            all_client[clientip] = client;
        }
    }

    std::string Client_Message(const std::string message,const std::string& clientip , const uint16_t clientport)
    {
        char buffer[1024];
        snprintf(buffer,sizeof(buffer), "[%s:%d] send a message: %s" , clientip.c_str() , clientport , message.c_str());

        return buffer;
    }


    // 运行服务器
    void Run(func_ func)
    {
        isrunning_ = true;
        lg_(Info, "running sucess ");
        char buffer[SIZE];
        while (true)
        {
            struct sockaddr_in client;
            bzero(&client, sizeof(client));
            unsigned int len = sizeof(client);

            int n = recvfrom(sockfd_, buffer, sizeof(buffer) - 1, 0, (sockaddr *)&client, &len);
            if (n < 0)
            {
                lg_(Warning, "recvfrom fail : errno message : %s , errno : %d ", strerror(errno), errno);
                continue;
            }

            // 读取用户的IP和端口
            buffer[n] = 0;
            uint16_t clientport = client.sin_port;
            std::string clientip = inet_ntoa(client.sin_addr);

            // 将用户信息存储起来
            New_Client(client, clientip , clientport);

            // 将用户的IP,端口和信息结合
            std::string ret =  Client_Message(buffer , clientip , clientport);

            // 将用户信息群发给所有用户
            for(auto& other : all_client) 
            {
                int sz = sizeof(other.second);
                sendto(sockfd_, ret.c_str(), ret.size(), 0, (sockaddr *)&other.second, sz);
            }

            // 处理信息
            // std::string info(buffer);
            // std::string ret =  func(info);

            // 发送回去
            //sendto(sockfd_, ret.c_str(), ret.size(), 0, (const sockaddr *)&client, len);
        }
    }

private:
    int sockfd_;     // 网络文件描述符
    uint16_t port_;  // 端口
    std::string ip_; // IP
    bool isrunning_; // 是否正在运行
    std::unordered_map<std::string,struct sockaddr_in> all_client;
};